<template>
	<!-- 海报分享 -->
	<view class="share-poster">
		<view class="share-qrcode">
			<view class="share-poster-title">
				<view style="width: 6upx;height: 32upx;background: #00A66A;border-radius: 3upx;margin-top: 6upx;"></view>
				<view style="margin-left: 14upx">
					分享素材
					<text>(分享微信好友，队员永久绑定)</text>
				</view>
			</view>
			<!--#ifdef H5-->
			<view class="poster-img"><image :src="share_img" :style="{ width: '100%', height: '100%' }" @click="preImg(share_img)"></image></view>
			<!--#endif-->
			
			<!--#ifdef MP-WEIXIN-->
			<canvas
				id="canvas"
				canvas-id="canvas"
				:style="{ width: posterWidth + 'px', height: posterHeight + 'px', position: 'fixed', zIndex: '-10', left: '0', top: '-9999px' }"
			></canvas>
			<view class="poster-img" id="posterImg">
				<view class="good-info" id="goodInfo">
					<!-- 商品主图 -->
					<image :src="goodInfo.mainImg" id="goodInfoImg" @click="preImg(share_img)"></image>
				</view>
				<image :src="textBgUrl" class="share_user" id="textBg"></image>
				<image :src="avatarUrl" id="avatarUrl"></image>
				<text id="nickName">{{ nickName }}</text>
				<!-- 二维码 -->
				<view class="qr-code"><image :src="path" id="qrCode"></image></view>
			</view>
			<view class="save-poster" @click="savePoster">保存你专属海报</view>
			<view class="save-succeed-tip" v-if="savePostSucc">
				<view style="font-size:28upx;">专属海报，保存成功！</view>
				<view class="arrow-down"></view>
			</view>
			<!--#endif-->
		</view>
		<view class="share-text">
			<view class="share-poster-title">
				<view style="width: 6upx;height: 32upx;background: #00A66A;border-radius: 3upx;margin-top: 4upx;"></view>
				<view style="margin-left: 14upx">分享文案</view>
			</view>
			<view>{{ text }}</view>
			<view class="copy-text" @click="copyText">复制文案</view>
		</view>
		<view class="earnings-scheme" v-if="income.mySelf.price > 0 || income.share.price > 0 || income.mySelf.achievement_value > 0 || income.share.achievement_value > 0">
			<view class="share-poster-title">
				<view style="width: 6upx;height: 32upx;background: #00A66A;border-radius: 3upx;margin-top: 4upx;"></view>
				<view style="margin-left: 14upx">
					收益方案
					<text>(邀请好友购买成功后)</text>
				</view>
			</view>
			<view class="buy-gift-type">
				<text>购买类型</text>
				<text>奖励类型</text>
			</view>
			<view class="buy-situation">
				<view class="buy_one" v-if="income.mySelf.price > 0 || income.mySelf.achievement_value > 0">
					<text>自己购买</text>
					<text>
						<text v-if="income.mySelf.price > 0">省￥{{ income.mySelf.price }}元</text>
						<text style="margin-left:18upx;" v-if="income.mySelf.achievement_value > 0">
							成就值
							<text style="color:#FF5C46 ;">+{{ income.mySelf.achievement_value }}</text>
						</text>
					</text>
				</view>
				<view v-if="income.share.price > 0 || income.share.achievement_value > 0">
					<text>分享赚钱</text>
					<text>
						<text v-if="income.share.price > 0">赚￥{{ income.share.price }}元</text>
						<text style="margin-left:18upx;" v-if="income.share.achievement_value > 0">
							成就值
							<text style="color: #FF5C46;">+{{ income.share.achievement_value }}</text>
						</text>
					</text>
				</view>
			</view>
		</view>
		<view class="service-share">
			<view>
				剩余名额
				<text style="color: #FF5C46;">{{ num }}</text>
				个
			</view>
			<view style="display: flex;align-items: center;">
				<view class="service" @click="toChat">
					<image :src="service_icon" mode="" style="width: 64upx;height: 64upx;"></image>
					<text>客服</text>
				</view>
				<view class="service-share-gain">
					<!--#ifdef H5-->
					<button style="font-weight: 550;font-size:30upx;background-color:#fff;" @click="open_share_tip">分享给好友</button>
					<!--#endif-->
					<!--#ifdef MP-WEIXIN-->
					<button open-type="share" style="font-weight: 550;font-size:30upx;background-color:#fff;">分享给好友</button>
					<!--#endif-->
					<text>
						<text v-if="income.share.price > 0">
							赚￥
							<text style="color:#FF5C46;">{{ income.share.price }}元</text>
						</text>
						<text style="margin-left:10upx;" v-if="income.share.achievement_value > 0">
							<text style="color:#FF5C46;">+{{ income.share.achievement_value }}成就值</text>
						</text>
					</text>
				</view>
				
				<!-- #ifdef H5 -->
				<!-- 分享提示 -->
				<uni-popup ref="shareTip" :custom="true">
					<view class="popup_box_de_share"><image class="popup_box_close_share" src="../../../static/share_tip.png"></image></view>
				</uni-popup>
				<!-- #endif -->
			</view>
		</view>
	</view>
</template>

<script>
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import h5Copy from '@/js_sdk/junyi-h5-copy/junyi-h5-copy.js';
let posterData = {
	posterImg: null,
	goodInfo: null,
	goodInfoImg: null,
	nickName: null,
	avatarUrl: null,
	qrCode: null,
	textBg: null
};
let systemInfo = null;
let query = null;
export default {
	components: { uniPopup },
	onShareAppMessage(res) {
		return {
			title: this.title,
			path: 'pages/welfare/welfareDetails/welfareDetails?id=' + this.id + '&share_id=' + this.userId + '&fromJin=2',
			imageUrl: this.goodInfo.mainImg
		};
	},
	data() {
		return {
			// 活动id
			id: 0,
			token: this.$store.getters.getToken,
			userId: this.$store.getters.getUserId,
			service_icon: this.$imgUrl + 'img/privilege/service_icon.png',
			textBgUrl: 'https://lightplanet.tuanhaoke.cn/img/text-bg.png',
			savePostSucc: false,
			// 生成的海报的本地路径
			generatePosterUrl: '',
			posterTop: 0,
			qrCodeImg: '',
			posterWidth: 0,
			posterHeight: 0,
			avatarUrl: '',
			nickName: '',
			income: {
				mySelf: {
					achievement_value: 0,
					price: 0.0
				},
				share: {
					achievement_value: 0,
					price: 0.0
				}
			},
			// 剩余名额
			num: 0,
			goodInfo: {
				mainImg: ''
			},
			text: '',
			title: '',
			share_img: null,
			path:null
		};
	},
	onLoad(options) {
		this.id = options.id;
		try {
			const res = uni.getStorageSync('userInfo');
			if (res) {
				this.nickName = res.nickName;
				this.avatarUrl = res.avatarUrl;
			}
		} catch (e) {
			this.nickName = this.$store.state.nickName;
			this.avatarUrl = this.$store.state.avatarUrl;
		}
		if (this.nickName.length > 3) {
			this.nickName = this.nickName.slice(0, 3);
		}
		uni.getSystemInfo({
			success: function(res) {
				systemInfo = res;
			}
		});
		//#ifdef MP-WEIXIN
		this.drawCanvas();
		//#endif
		//#ifdef H5
		this.getInfo();
		//#endif
	},
	methods: {
		// 获取分享的信息
		getInfo() {
			return new Promise((resolve, reject) => {
				let data = {
					token: this.token,
					id: this.id,
					page: 'pages/welfare/welfareDetails/welfareDetails?id=' + this.id + '&share_id=' + this.userId + '&fromJin=2'
				};
				this.$api
					.get_privi_share_info(data)
					.then(res => {
						if (res.status) {
							this.goodInfo.mainImg = res.data.img_src;
							this.title = res.data.title;
							this.income = res.data.income;
							this.text = res.data.share_copy;
							this.num = res.data.num;
							this.path = res.data.path 
							//#ifdef MP-WEIXIN
							this.share_img = res.data.share_img;
							//#endif
							//#ifdef H5
							this.share_img = res.data.h5share_img;
							//#endif
							let link = this.$store.state.H5URL + 'pages/welfare/welfareDetails/welfareDetails?id=' + this.id + '&share_id=' + this.userId + '&fromJin=2';
							this.share(this.title, this.text, this.goodInfo.mainImg, (link = link));
							resolve(res.data.path);
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
						console.log('获取分享的信息', res);
					})
					.catch(err => {
						reject();
						console.log('获取分享的信息', err);
					});
			});
		},
		toChat() {
			uni.navigateTo({
				url: '../../service/service'
			});
		},
		// 复制分享文案
		copyText() {
			//#ifdef MP-WEIXIN
			let self = this;
			uni.setClipboardData({
				data: self.text,
				success: function() {
					console.log('success');
				},
				fail: function() {
					uni.showToast({
						title: '复制失败，请稍后重试！',
						icon: 'none',
						duration: 2000
					});
				}
			});
			//#endif
			//#ifdef H5
			let that = this; // 复制内容，必须字符串，数字需要转换为字符串
			const result = h5Copy(that.text);
			if (result === false) {
				uni.showToast({
					title: '不支持'
				});
			} else {
				uni.showToast({
					title: '复制成功',
					icon: 'none'
				});
			}
			//#endif
		},
		downloadImg(url) {
			return new Promise((resolve, reject) => {
				uni.downloadFile({
					url: url,
					success: res => {
						if (res.statusCode === 200) {
							resolve(res.tempFilePath);
						} else {
							reject();
						}
					},
					fail: e => {
						console.log('下载图片失败', e);
						reject();
					}
				});
			});
		},
		open_share_tip() {
			this.$refs.shareTip.open();
		},
		// getPosterImg(){
		// 	return new Promise((resolve, reject) => {
		// 			let data = {
		// 				goodId: 90035,
		// 				merchantID: 1,
		// 				page: 'pages/productDetails/productDetails',
		// 				token: '7eLahEBRMiQnxCVmkoP6'
		// 			}
		// 			this.$api.get_poster_image(data).then(res => {
		// 				resolve(res.imgurl)
		// 			}).catch(err => {
		// 				console.log(err)
		// 				reject()
		// 			})
		// 	})
		// },
		drawCanvas() {
			let self = this;
			this.getInfo()
				.then(res => {
					uni.showLoading({
						title: '海报生成中',
						mask: true
					});
					this.qrCodeImg = res + '?id=' + self.id + '&share_id=' + self.userId;
					let p1 = this.downloadImg(this.qrCodeImg);
					let p2 = this.downloadImg(this.goodInfo.mainImg);
					let p3 = this.downloadImg(this.avatarUrl);
					let p4 = this.downloadImg(this.textBgUrl);
					Promise.all([p1, p2, p3, p4])
						.then(([qrCodeImg, goodImg, avatarUrl, textBgUrl]) => {
							query = uni.createSelectorQuery().in(self);
							query.select('#posterImg').boundingClientRect(data => {
								posterData.posterImg = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.select('#goodInfo').boundingClientRect(data => {
								posterData.goodInfo = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.select('#goodInfoImg').boundingClientRect(data => {
								posterData.goodInfoImg = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.select('#nickName').boundingClientRect(data => {
								posterData.nickName = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.select('#avatarUrl').boundingClientRect(data => {
								posterData.avatarUrl = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.select('#qrCode').boundingClientRect(data => {
								posterData.qrCode = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.select('#textBg').boundingClientRect(data => {
								posterData.textBg = {
									width: data.width,
									height: data.height,
									top: data.top,
									left: data.left
								};
							});
							query.exec(data => {
								let x = posterData.posterImg.left;
								let y = posterData.posterImg.top;
								self.posterWidth = posterData.posterImg.width;
								self.posterHeight = posterData.posterImg.height;
								console.log('posterData posterData posterData', posterData);
								for (let key in posterData) {
									posterData[key].left -= x;
									posterData[key].top -= y;
								}
								const context = uni.createCanvasContext('canvas', self);

								context.drawImage(goodImg, posterData.goodInfoImg.left, posterData.goodInfoImg.top, posterData.goodInfoImg.width, posterData.goodInfoImg.height);

								context.setTextAlign('left');
								context.setTextBaseline('top');
								context.setFontSize(uni.upx2px(24));
								context.fillStyle = '#333';
								self.drawText(context, self.nickName, posterData.nickName.left, posterData.nickName.top, posterData.nickName.width, 24, 1.2);

								context.closePath();
								context.stroke();
								//商品详情页面二维码
								context.drawImage(qrCodeImg, posterData.qrCode.left, posterData.qrCode.top, posterData.qrCode.width, posterData.qrCode.height);
								context.drawImage(textBgUrl, posterData.textBg.left, posterData.textBg.top, posterData.textBg.width, posterData.textBg.height);
								context.save();
								context.beginPath();
								context.arc(
									posterData.avatarUrl.left + posterData.avatarUrl.width / 2,
									posterData.avatarUrl.top + posterData.avatarUrl.height / 2,
									posterData.avatarUrl.height / 2,
									0,
									2 * Math.PI
								);
								context.clip();
								context.drawImage(avatarUrl, posterData.avatarUrl.left, posterData.avatarUrl.top, posterData.avatarUrl.width, posterData.avatarUrl.height);
								context.restore();

								context.draw(false, () => {
									setTimeout(() => {
										self.generatePoster();
									}, 100);
								});
								query = null;
							});
						})
						.catch(() => {
							uni.showToast({
								// title: '海报生成失败,请重试',
								// icon: 'none',
								// duration: 1500
							});
						});
				})
				.catch(() => {
					uni.showToast({
						// title: '海报生成失败,请重试',
						// icon: 'none',
						// duration: 1500
					});
				});
		},
		generatePoster() {
			let self = this;
			uni.canvasToTempFilePath(
				{
					x: 0,
					y: 0,
					width: self.posterWidth,
					height: self.posterHeight,
					destWidth: self.posterWidth * systemInfo.pixelRatio,
					destHeight: self.posterHeight * systemInfo.pixelRatio,
					quality: 1,
					canvasId: 'canvas',
					success: function(res) {
						uni.hideLoading();
						self.generatePosterUrl = res.tempFilePath;
						let shareBottomHeight, generatePosterImgHeight;
						self.$nextTick(() => {
							query = uni.createSelectorQuery().in(self);
							query.exec(data => {
								self.posterTop = systemInfo.windowHeight / 2;
								query = null;
							});
						});
					},
					fail(e) {
						setTimeout(() => {
							self.generatePoster();
						}, 1000);
						// uni.hideLoading()
						// uni.showToast({
						// 	title: '海报生成失败，请重试',
						// 	duration: 1500,
						// 	icon: 'none'
						// })
					}
				},
				self
			);
		},
		drawText(context, t, x, y, w, s, lineHeight) {
			var chr = t.split('');
			var temp = '';
			var row = [];
			for (var a = 0; a < chr.length; a++) {
				if (context.measureText(temp).width < w && context.measureText(temp + chr[a]).width <= w) {
					temp += chr[a];
				} else {
					row.push(temp);
					temp = chr[a];
				}
			}
			row.push(temp);

			if (row.length >= 3) {
				row[1] = row[1].split('');
				row[1].pop();
				row[1].push('...');
				row[1] = row[1].join('');
			}
			for (var b = 0; b < row.length; b++) {
				if (b <= 1) {
					context.fillText(row[b], x, y + b * uni.upx2px(s) * lineHeight);
				} else {
					break;
				}
			}
		},
		savePoster() {
            let that = this;
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success() {
                    uni.downloadFile({
                       url: that.share_img,
                       success: function (res) {
                           uni.saveImageToPhotosAlbum({
                           	filePath: res.tempFilePath,
                           	success: function(res) {
                           		that.savePostSucc = true;
                           	},
                           	fail: function(err) {
                           		uni.showToast({
                           			title: '保存失败，请确认是否授权相册！',
                           			icon: 'none',   
                           			duration: 2000
                           		});
                           		that.savePostSucc = false;
                           	}
                           });
                       },
                       fail: function (res) {
                           console.log('失败')
                       }
                    });
					
				},
				fail() {
					uni.showModal({
						content: '拒绝授权相册权限后无法成功保存海报，是否重新授权？',
						confirmColor: '#00A66A',
						success: function(res) {
							if (res.confirm) {
								uni.openSetting({
									success(res) {
										console.log(res.authSetting);
									}
								});
							} else if (res.cancel) {
							}
						}
					});
				}
			});
            
		}
	}
};
</script>

<style lang="scss">
.buy_one {
	border-bottom: 1upx solid #dedede;
}

page {
	position: relative;
	padding-bottom: 308upx;
}

.share-poster {
	width: 100%;
	height: 100%;
	background: #f5f6f9;
}

.share-qrcode {
	width: 100%;
	height: 1110upx;
	background: #fff;
	padding: 0 30upx;
	box-sizing: border-box;
	position: relative;
}

.share-poster-title {
	padding: 22upx 0;
	box-sizing: border-box;
	border-bottom: 0.5px solid #dedede;
	font-size: 30upx;
	color: #333;
	line-height: 42upx;
	display: flex;
}

.share-poster-title text {
	display: inline-block;
	margin-left: 20upx;
	color: #999999;
	font-size: 24upx;
}

.save-poster {
	width: 430upx;
	height: 80upx;
	line-height: 80upx;
	color: #fff;
	text-align: center;
	background: linear-gradient(#cbec00, #00a66a);
	box-shadow: 0 8upx 16upx 0 rgba(0, 166, 106, 0.4);
	border-radius: 40upx;
	margin: 0 auto;
	font-size: 30upx;
}

.share-text {
	width: 100%;
	background: #fff;
	padding: 0 30upx;
	box-sizing: border-box;
	margin-top: 20upx;
	padding-bottom: 40upx;
}

.share-text > view:nth-child(2) {
	color: #666666;
	font-size: 28upx;
	margin-top: 22upx;
	margin-bottom: 80upx;
}

.copy-text {
	width: 430upx;
	height: 80upx;
	line-height: 80upx;
	text-align: center;
	border: 1px solid #00a66a;
	border-radius: 40upx;
	color: #00a66a;
	font-size: 30upx;
	margin: 0 auto;
	font-weight: 550;
}

.save-succeed-tip {
	width: 432upx;
	height: 90upx;
	position: absolute;
	bottom: 130upx;
	left: 160upx;
}

.save-succeed-tip > view:first-child {
	width: 100%;
	height: 72upx;
	background: rgba(0, 0, 0, 0.8);
	border-radius: 16upx;
	text-align: center;
	color: #fff;
	line-height: 72upx;
}

.save-succeed-tip > view:last-child {
	width: 0;
	height: 0;
	border-width: 18upx;
	border-style: solid;
	border-color: rgba(0, 0, 0, 0.8) transparent transparent transparent;
	margin-left: 200upx;
}

.earnings-scheme {
	width: 1005;
	// height: 442upx;
	background: #fff;
	margin-top: 20upx;
	padding: 0 30upx;
	margin-bottom: 30upx;
	box-sizing: border-box;
}

.buy-gift-type {
	width: 100%;
	height: 80upx;
	margin-top: 30upx;
	line-height: 80upx;
	text-align: center;
	background: #f2f2f2;
}

.buy-gift-type > text {
	display: inline-block;
	width: 50%;
	color: #333;
	font-size: 28upx;
}

.buy-situation > view {
	padding: 40upx 0;
	box-sizing: border-box;
	display: flex;
	justify-content: space-between;
}

.buy-situation text {
	display: inline-block;
	color: #666666;
	font-size: 30upx;
	line-height: 42upx;
}

.service-share {
	width: 100%;
	height: 308upx;
	background: #fff;
	border-top-left-radius: 16upx;
	border-top-right-radius: 16upx;
	box-shadow: 0 -6upx 22upx 0 rgba(109, 107, 107, 0.27);
	position: fixed;
	bottom: 0;
}

.service-share > view:first-child {
	border-bottom: 0.5px solid #dedede;
	text-align: center;
	color: #333333;
	font-size: 26upx;
	padding: 20upx 0;
	box-sizing: border-box;
}

.service-share > view:last-child {
	padding: 20upx 0;
	box-sizing: border-box;
	border-bottom: 0.5px solid #dedede;
}

.service {
	color: #666;
	font-size: 22upx;
	margin-left: 48upx;
	margin-top: 22upx;
}

.service > text {
	display: block;
	width: 64upx;
	text-align: center;
	line-height: 32upx;
}

.service-share-gain {
	width: 430upx;
	margin-left: 112upx;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.service-share-gain > button {
	width: 100%;
	height: 80upx;
	border: 1px solid #00a66a;
	line-height: 80upx;
	color: #00a66a;
	margin-bottom: 10upx;
	border-radius: 40upx;
}

.service-share-gain > text {
	display: inline-block;
	width: 100%;
	color: #999;
	font-size: 22upx;
	line-height: 34upx;
}

.poster-img {
	width: 462upx;
	height: 820upx;
	left: 0;
	top: -9999px;
	right: 0;
	margin: 40upx auto;
	box-sizing: border-box;
	border-radius: 10upx;
	text {
		line-height: 1.2;
	}
	.good-info {
		image {
			display: block;
			width: 462upx;
			height: 820upx;
		}
	}
	#avatarUrl {
		width: 50upx;
		height: 50upx;
		border-radius: 50%;
		position: absolute;
		top: 160upx;
		left: 174upx;
	}
	#nickName {
		width: 74upx;
		height: 34upx;
		font-size: 24upx;
		color: #333;
		position: absolute;
		top: 170upx;
		left: 228upx;
	}
	.share_user {
		width: 140upx;
		height: 50upx;
		position: absolute;
		top: 160upx;
		left: 174upx;
	}
	.qr-code {
		image {
			width: 110upx;
			height: 110upx;
			position: absolute;
			bottom: 190upx;
			right: 176upx;
		}
	}
}
// 分享提示
.popup_box_de_share {
	width: 100%;
	height: 100%;
}
.popup_box_close_share {
	width: 300upx;
	height: 300upx;
	position: fixed;
	top: 10upx;
	right: 10upx;
}
.popup_box_title {
	display: flex;
	justify-content: space-between;
}
.popup_box_title > view:nth-child(2) {
	color: #333333;
	font-size: 34upx;
}
.popup_box_title_tip {
	color: #999999;
	font-size: 24upx;
	text-align: center;
	margin-top: 10upx;
}
.popup_box_tip {
	color: #666666;
	font-size: 26upx;
	text-align: center;
}
.popup_box_title > .line {
	width: 84upx;
	height: 2upx;
	border-top: 1upx solid #dedede;
	margin-top: 24upx;
}
.popup_box_de {
	width: 592upx;
	height: 744upx;
	position: relative;
	z-index: 999;
}
.popup_box_close {
	width: 52upx;
	height: 52upx;
	position: absolute;
	top: 0;
	right: 0;
}
.popup_box_content {
	width: 100%;
	height: 682upx;
	background: #ffffff;
	position: absolute;
	top: 72upx;
	left: 0;
	border-radius: 16upx;
	z-index: 999;
	padding: 40upx 46upx;
	box-sizing: border-box;
}
.popup_box_content > image {
	width: 388upx;
	height: 386upx;
	margin: 24upx auto 0;
	margin-left: 40upx;
}
</style>
